//
//  BannerCard.swift
//  shop
//
//  Created by chen on 2025/5/13.
//

import SwiftUI
import Kingfisher

struct BannerCard: View {
    
    @State private var bannerIndex: Int = 0
    
    @ObservedObject var vm: HomeViewModel
    @ObservedObject var router: Router
    
    // 定时器
    let timer = Timer.publish(every: 3, on: .main, in: .common).autoconnect()
    
    var body: some View {
        TabView(selection: $bannerIndex) {
            ForEach(0..<vm.banners.count, id: \.self) { index in
                Button {
                    router.to(.detailView(id: vm.banners[index].id))
                } label: {
                    KFImage.url(URL(string: vm.banners[index].img))
                           .loadDiskFileSynchronously()
                           .cacheMemoryOnly()
                           .fade(duration: 0.25)
                           .resizable()
                           .scaledToFill()
                           .tag(index)
                }
                .buttonStyle(PlainButtonStyle())
            }
        }
        .tabViewStyle(PageTabViewStyle())
        .frame(height: 210) // 设置轮播图高度
        .background(.white)
        .cornerRadius(10)
        .onReceive(timer) { _ in
            // 自动轮播
            withAnimation {
                if vm.banners.count > 0 {
                    bannerIndex = (bannerIndex + 1) % vm.banners.count
                }
            }
        }
        .padding(.horizontal, 10)
        .onAppear{
            vm.getBanners()
        }
    }
}

#Preview {
    BannerCard(vm: HomeViewModel.shared, router: Router.shared)
}
